<!-- 智能体 -->
<script lang="ts" setup>
import type { AgentTableData, PageTableRequestData } from "@/common/apis/intelligent/type.ts"
import type { FormInstance } from "element-plus"
import { deleteAgentDataApi, downloadAgentApi, getAgentDataApi, getAgentTypeOptionsApi } from "@/common/apis/intelligent"
import { getProjectId } from "@/common/utils/cache/local-storage"
import { parseSearchDate } from "@/common/utils/datetime"
import { downloadFile } from "@/common/utils/fileUtils"
import Card from "@@/components/CardItem/card.vue"
import { usePagination } from "@@/composables/usePagination"
import { agentSupportSideMap, FormTypeEnum } from "@@/constants/other-keys"
import { Refresh, Search } from "@element-plus/icons-vue"
import { ref, watch } from "vue"
import XEUtils from "xe-utils"
import { CreateOrUpdate, ImportFromResource, SaveAs } from "./components/index"
import { useAutoRefresh } from "@/layouts/composables/useAutoRefresh";
import { usePermissionStore } from "@/pinia/stores/permission"
import { isEmpty } from "lodash-es"

defineOptions({
  // 命名当前组件
  name: "IntelligentIndex"
})

const router = useRouter()
const agentTypeOptions = ref<string[]>([])
const isGrid = ref<boolean>(true)
const searchMore = ref<boolean>(false)
const searchFormRef = ref<FormInstance | null>(null)
const searchKey = ref()
const loading = ref<boolean>(false)
const tableData = ref<AgentTableData[]>([])
const multipleSelection = ref<AgentTableData[]>([])
const dialogType = ref<FormTypeEnum>(FormTypeEnum.VIEW)
const dialogVisibleUpload = ref<boolean>(false)
const dialogVisibleImport = ref<boolean>(false)
const saveAsVisible = ref<boolean>(false)
const curId = ref<string>()
const TableRef = ref()
const { paginationData, handleSizeChange, handleCurrentChange } = usePagination()

function handleCreate() {
  if (getProjectId()) {
    router.replace({ name: "MyProjectIntelligentCreate" })
  } else {
    router.replace({ name: "IntelligentCreate" })
  }
}
function resetSearch() {
  searchFormRef.value?.resetFields()
  handleSearch()
}
function handleSearchMore() {
  searchMore.value = !searchMore.value
  if (!searchMore.value) {
    resetSearch()
  }
}
const searchData = reactive<PageTableRequestData>({
  agent_type: undefined,
  agent_name: undefined,
  create_time: undefined,
  end_time: undefined,
  time_range: undefined,
  project_id: getProjectId(),
  current_page: 0
})
function getTableData() {
  loading.value = true
  const params: PageTableRequestData = {
    size: paginationData.pageSize,
    current_page: paginationData.currentPage,
    agent_name: undefined,
    agent_type: undefined,
    create_time: undefined,
    end_time: undefined,
    ...(!isEmpty(getProjectId()) ? { project_id: getProjectId() } : {}),
    ...(!isEmpty(searchKey.value) ? { search_key: searchKey.value } : {})
  }
  if (searchMore.value) {
    params.agent_name = searchData.agent_name
    params.agent_type = searchData.agent_type
    if (searchData.time_range && searchData.time_range.length == 2) {
      params.create_time = searchData.time_range[0]
      params.end_time = parseSearchDate(searchData.time_range[1])
    }
  }
  getAgentDataApi(params)
    .then(({ data }) => {
      tableData.value = data.rows
      paginationData.total = data.total
    })
    .catch(() => {
      tableData.value = []
    })
    .finally(() => {
      loading.value = false
    })
}
function handleSearch() {
  paginationData.currentPage === 1 ? getTableData() : (paginationData.currentPage = 1)
}
function handleUploadCreate() {
  nextTick(() => {
    dialogVisibleUpload.value = true
  })
}
function handleImportCreate() {
  nextTick(() => {
    dialogVisibleImport.value = true
  })
}
function handleRowCurrentChange(val: AgentTableData | undefined) {
  if (val == undefined) {
    return
  }
  curId.value = val?.agent_id
  dialogType.value = FormTypeEnum.VIEW
}
function handleSelectionChange(val: AgentTableData[]) {
  multipleSelection.value = val
}
function handleMultipleDelete() {
  const ids: string[] = []
  const names: string[] = []
  multipleSelection.value.forEach((item) => {
    ids.push(item.agent_id as string)
    names.push(item.agent_name)
  })
  ElMessageBox.confirm(`正在删除智能体：${names.join("，")}，确认删除？`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(() => {
    deleteAgentDataApi(ids).then(() => {
      ElMessage.success("删除成功")
      hanldeClearSelection()
      getTableData()
    })
  })
}
function hanldeClearSelection() {
  nextTick(() => {
    TableRef.value.clearSelection()
  })
}
function getRowKeys(row: AgentTableData) {
  return row.agent_id
}
function closeDialogUpload(param: string | undefined) {
  dialogVisibleUpload.value = false
  TableRef.value!.setCurrentRow(null)
  if (param && param === "refresh") getTableData()
}
function closeDialogImport(param: string | undefined) {
  dialogVisibleImport.value = false
  TableRef.value!.setCurrentRow(null)
  if (param && param === "refresh") getTableData()
}
// #region
function handleDownload(row: AgentTableData) {
  row.agent_id
  && downloadAgentApi(row.agent_id).then((res) => {
    downloadFile(res)
  })
}
// #endregion
// #region 删
function handleDelete(row: AgentTableData) {
  ElMessageBox.confirm(`正在删除智能体：${row.agent_name}，确认删除？`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(() => {
    deleteAgentDataApi([row.agent_id]).then(() => {
      ElMessage.success("删除成功")
      hanldeClearSelection()
      getTableData()
    })
  })
}
// #endregion
// #region 详情
function handleView(row: AgentTableData) {
  if (getProjectId()) {
    router.replace({ name: "MyProjectIntelligentView", query: { id: row.agent_id } })
  } else {
    router.replace({ name: "IntelligentView", query: { id: row.agent_id } })
  }
}
// #endregion

function handleToggleSelect(row: AgentTableData) {
  TableRef.value!.toggleRowSelection(row, undefined, false)
}

function handleSaveAs(row: AgentTableData) {
  curId.value = row.agent_id
  saveAsVisible.value = true
}
function handleSaveAsClose(param: string | undefined) {
  saveAsVisible.value = false
  curId.value = undefined
  TableRef.value!.setCurrentRow(null)
  if (param && param === "refresh") getTableData()
}

function getAgentTypeOptions() {
  getAgentTypeOptionsApi().then(({ data }) => {
    agentTypeOptions.value = data.type
  })
}
getAgentTypeOptions()
useAutoRefresh(getTableData)
/** 监听分页参数的变化 */
watch([() => paginationData.currentPage, () => paginationData.pageSize], getTableData, { immediate: true })

const selectedId = computed(() => {
  if (multipleSelection.value !== undefined && multipleSelection.value.length > 0) {
    const ids = XEUtils.map(multipleSelection.value, (item) => {
      return item.agent_id
    })
    return ids
  }
  return []
})
</script>

<template>
  <div class="app-container pager-container">
    <div class="cc-search">
      <div class="cc-search-common">
        <el-input v-model="searchKey" size="large" placeholder="请输入搜索内容" class="csc-search-input" @keydown.enter="handleSearch">
          <template #append>
            <el-button :icon="Search" v-throttle="() => handleSearch()" />
          </template>
        </el-input>
        <div class="csc-more" @click="handleSearchMore">
          <span>更多</span>
          <el-icon v-if="!searchMore">
            <ArrowDown />
          </el-icon>
          <el-icon v-else>
            <ArrowUp />
          </el-icon>
        </div>
      </div>
      <div class="cc-search-common-more" v-if="searchMore">
        <el-form ref="searchFormRef" :model="searchData" :inline="true">
          <el-form-item prop="agent_name" label="智能体名称">
            <el-input v-model="searchData.agent_name" @change="handleSearch()" placeholder="请输入" />
          </el-form-item>
          <el-form-item prop="agent_type" label="智能体类型">
            <el-select
              v-model="searchData.agent_type" clearable placeholder="请选择" style="width: 240px"
              @change="handleSearch()"
            >
              <el-option v-for="item in agentTypeOptions" :key="item" :label="item" :value="item" />
            </el-select>
          </el-form-item>
          <el-form-item prop="time_range" label="时间范围">
            <el-date-picker
              v-model="searchData.time_range" type="daterange" unlink-panels range-separator="至"
              value-format="YYYY-MM-DD" start-placeholder="开始时间" end-placeholder="结束时间" @change="handleSearch()"
            />
          </el-form-item>
          <el-form-item>
            <el-button :icon="Refresh" @click="resetSearch">
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
    <div v-loading="loading" class="content-other">
      <div class="flex-between mb-main-padding">
        <div class="flex-y-center tag">
          <el-button v-if="getProjectId() != null" type="primary" @click="handleCreate">
            新建
          </el-button>
          <el-button v-if="getProjectId() != null" type="primary" @click="handleImportCreate">
            导入
          </el-button>
          <el-button v-if="getProjectId() != null" type="primary" @click="handleUploadCreate">
            本地上传
          </el-button>
          <el-button
            :disabled="multipleSelection.length < 1" type="danger"
            @click="handleMultipleDelete"
          >
            批量删除
          </el-button>
        </div>
        <div class="flex-y-center sh-operate">
          <div class="sh-btn" :class="{ active: isGrid }" @click="() => isGrid = true">
            <el-tooltip content="卡片" placement="bottom">
              <SvgIcon name="table-grid" />
            </el-tooltip>
          </div>
          <div class="sh-btn" :class="{ active: !isGrid }" @click="() => isGrid = false">
            <el-tooltip content="列表" placement="bottom">
              <SvgIcon name="table-list" />
            </el-tooltip>
          </div>
        </div>
      </div>
      <div v-show="isGrid" class="cpi-content-main">
        <div class="custom-card-container">
          <template v-for="(item, index) in tableData" :key="index">
            <Card
              :tag="item.agent_type"
              :name="item.agent_name"
              :description="item.agent_describe == null ? '' : item.agent_describe"
              :create-by="item.create_user.user_name"
              :create-time="item.create_time"
              :data="item"
              :selected="selectedId.includes(item.agent_id as string)"
              :is-download="true"
              :is-save-as="true"
              @handle-download="handleDownload"
              @handle-delete="handleDelete"
              @handle-view="handleView"
              @handle-save-as="handleSaveAs"
              @toggle-select="handleToggleSelect"
            />
          </template>
        </div>
      </div>
      <div v-show="!isGrid" class="cpi-content-main">
        <el-auto-resizer>
          <template #default="{ height, width }">
            <el-table
              ref="TableRef" v-loading="loading" :data="tableData" :row-key="getRowKeys" :width="width"
              :height="height" @current-change="handleRowCurrentChange" @selection-change="handleSelectionChange"
            >
              <el-table-column type="selection" header-align="left" :reserve-selection="true" width="55" />
              <el-table-column
                prop="agent_name" show-overflow-tooltip label="名称" header-align="left"
                min-width="150"
              />
              <el-table-column prop="agent_type" label="类型" header-align="left" min-width="150" />
              <el-table-column prop="agent_support_side" label="支持阵营" header-align="left" min-width="150">
                <template #default="{ row }">
                  {{ agentSupportSideMap[row.agent_support_side] }}
                </template>
              </el-table-column>
              <el-table-column
                prop="agent_describe" show-overflow-tooltip label="描述" header-align="left"
                min-width="180"
              />
              <el-table-column
                prop="create_user.user_name" sortable label="创建人" header-align="left"
                min-width="120"
              />
              <el-table-column prop="create_time" sortable label="创建时间" header-align="left" min-width="120" />
              <el-table-column fixed="right" label="操作" align="center" width="140">
                <template #default="scope">
                  <el-space :size="12">
                    <el-link :underline="false" @click.stop v-throttle="() => handleView(scope.row)" title="查看">
                      <el-icon :size="18">
                        <View />
                      </el-icon>
                    </el-link>
                    <el-link :underline="false" @click.stop v-throttle="() => handleDownload(scope.row)" title="下载">
                      <el-icon :size="18">
                        <Download />
                      </el-icon>
                    </el-link>
                    <el-link v-if="getProjectId() != null" :underline="false" @click.stop v-throttle="() => handleSaveAs(scope.row)" title="另存为">
                      <el-icon :size="18">
                        <DocumentAdd />
                      </el-icon>
                    </el-link>
                    <el-link :underline="false" type="danger" @click.stop v-throttle="() => handleDelete(scope.row)" title="删除">
                      <el-icon :size="18">
                        <Delete />
                      </el-icon>
                    </el-link>
                  </el-space>
                </template>
              </el-table-column>
            </el-table>
          </template>
        </el-auto-resizer>
      </div>
    </div>
    <div class="pager-wrapper">
      <el-pagination
        background
        layout="total, sizes, ->, prev, pager, next, jumper"
        :disabled="loading"
        :page-sizes="paginationData.pageSizes"
        :total="paginationData.total"
        :page-size="paginationData.pageSize"
        :current-page="paginationData.currentPage"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <CreateOrUpdate :id="undefined" :dialog-type="FormTypeEnum.CREATE" :visible="dialogVisibleUpload" @close-dialog="closeDialogUpload" />
    <ImportFromResource :visible="dialogVisibleImport" @close-dialog="closeDialogImport" />

    <SaveAs :id="curId" :visible="saveAsVisible" @close-dialog="handleSaveAsClose" />
  </div>
</template>

<style lang="scss" scoped>
@import "@@/assets/styles/main-page.scss";
@import "@@/assets/styles/mixins.scss";
</style>
